package com.chenwc.serialassistant.threadpool.task;

import com.chenwc.serialassistant.util.Common;
import com.chenwc.serialassistant.util.cpdetector.CpdetectorUtils;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.scene.control.Alert;
import javafx.scene.control.TextArea;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.nio.file.Files;

/**
 * 读取文件内容
 *
 * @author chenwc
 */
public class GetFileContentTask extends Task<Void> {

    /**
     * 任务名称
     */
    private final String name;

    private final static Logger logger = LoggerFactory.getLogger(GetFileContentTask.class);

    private final TextArea displayTextArea;

    private final File file;

    private final long handleDisplayBufferUpperLimit;

    /**
     * 构造函数
     */
    public GetFileContentTask(String name, TextArea displayTextArea, long handleDisplayBufferUpperLimit, File file) {
        this.name = name;
        this.displayTextArea = displayTextArea;
        this.handleDisplayBufferUpperLimit = handleDisplayBufferUpperLimit;
        this.file = file;
    }

    @Override
    protected Void call() {

        if (file == null || !file.exists()) {
            Common.alert(Alert.AlertType.WARNING, "警告", "打开的文件为空或者不存在！");
            return null;
        }

        // 此处的读取文件编码格式只是为了解决显示汉字乱码的问题
        String charsetName = CpdetectorUtils.getFileCharset(file.getAbsolutePath());
        logger.info("Open File CharsetName: {}", charsetName);

        Platform.runLater(() -> {
            //文件内容的读取
            InputStreamReader reader = null;
            BufferedReader bfreader = null;
            try {
                //InputStreamReader类是从字节流到字符流的桥接器：它使用指定的字符集读取字节并将它们解码为字符
                reader = new InputStreamReader(Files.newInputStream(file.toPath()), charsetName);
                //BufferedReader类从字符输入流中读取文本并缓冲字符，以便有效地读取字符，数组和行
                bfreader = new BufferedReader(reader);
                displayTextArea.setText("文件大小: " + file.length() + " 字节，下面是预览的前 " + 10 + " 行内容：\n");
                //缓冲BufferedReader读取的每一行字符
                String line;
                //包含该行内容的字符串，不包含任何行终止符，如果已到达流末尾，则返回 null
                int i = 10;
                while (((line = bfreader.readLine()) != null) && (i-- > 0)) {
                    if (displayTextArea.getText().length() < handleDisplayBufferUpperLimit) {
                        displayTextArea.appendText(line + "\n");
                    } else {
                        displayTextArea.appendText("已达显示区缓冲上限！\n");
                        break;
                    }
                }
            } catch (Exception e) {
                logger.error("Exception", e);
            } finally {
                IOUtils.closeQuietly(reader);
                IOUtils.closeQuietly(bfreader);
            }
        });

        return null;
    }

    @Override
    protected void succeeded() {
        super.succeeded();
        updateMessage("Done!");
        logger.info("{} is Done!", this);
    }

    @Override
    protected void cancelled() {
        super.cancelled();
        updateMessage("Cancelled!");
        logger.info("{} is Cancelled!", this);
    }

    @Override
    protected void failed() {
        super.failed();
        updateMessage("Failed!");
        logger.info("{} is Failed!", this);
    }

    @Override
    protected void running() {
        super.running();
        updateMessage("Running!");
        logger.info("{} is Running!", this);
    }

    @Override
    protected void scheduled() {
        super.scheduled();
        updateMessage("Scheduled!");
        logger.info("{} is Scheduled!", this);
    }

    /**
     * 获取任务名称
     *
     * @return 任务名称
     */
    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "GetFileContentTask [ name = " + name + " ]";
    }
}
